﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;

namespace ERPStore.Web.ModelMetadata
{
	public class ModelMetadataDefinition<TModel>
	{
		private IList<ModelMetaData> m_Config;

		public ModelMetadataDefinition()
		{
			m_Config = new List<ModelMetaData>();
		}

		public ModelMetaDataBuilder<TModel, TValue> SetMetadataFor<TValue>(Expression<Func<TModel, TValue>> expression)
		{
			var propertyName = GetPropertyFromExpression(expression);
			var mdi = new ModelMetaData()
			{
				ModelType = typeof(TModel),
				PropertyName = propertyName,
			};

			m_Config.Add(mdi);

			return new ModelMetaDataBuilder<TModel, TValue>(mdi);
		}

		public IList<ModelMetaData> List
		{
			get
			{
				return m_Config;
			}
		}

		public string GetPropertyFromExpression<TValue>(Expression<Func<TModel, TValue>> expression)
		{
			MemberExpression memberExpression = null;
			var unaryExpression = expression.Body as UnaryExpression;
			if (unaryExpression == null)
			{
				memberExpression = expression.Body as MemberExpression;
			}
			else
			{
				memberExpression = unaryExpression.Operand as MemberExpression;

			}
			var propertyName = memberExpression.Member.Name;
			return propertyName;
		}

	}
}
